import { createElement, useEffect, useState } from 'rax';
import { getSearchParams } from 'rax-app';
import View from 'rax-view';
import Image from 'rax-image';
import Text from 'rax-text';
import {
	getStorageSync,
} from '@/utils/util';
import {
  postUserArchivesAdd
} from '@/api';
import photoMask from '@/assets/images/photoMask.png';
import overturnIcon from '@/assets/images/overturn.png';
import cloud from '@tbmp/mp-cloud-sdk';
cloud.init({
  env: 'test',
})
import './index.css';

const CameraSection = () => {
  const [canSubmit, setCanSubmit] = useState(true);
  const [canPhoto, setCanPhoto] = useState(true);
  const [photo, setPhoto] = useState('');
  const [hasResult, setHasResult] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [error, setError] = useState('');
  const [top, setTop] = useState(0);
  const [errorsList] = useState([
    {
      id: 0,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_side.png',
      name: '侧面'
    },
    {
      id: 1,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_occlusion.png',
      name: '有遮挡'
    },
    {
      id: 2,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_dark.png',
      name: '光线暗'
    },
    {
      id: 3,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_vague.png',
      name: '模糊'
    }
  ]);
  const [positionType, setPositionType] = useState('front');

  useEffect(()=>{
    my.getSystemInfo({
      success: (res) => {
        setTop(res.statusBarHeight + res.titleBarHeight)
      }
    });
    let params = getSearchParams();
    if (params.url) {
      setPhoto(params.url);
      setHasResult(true);
      if (params.isError == 1 || params.suggestion != 'pass') {
        setError(params.error);
        setIsOpen(true);
      }
    }
  }, []);

  const takePhoto = () => {
    const ctx = my.createCameraContext('camera_take');
    if (canPhoto) {
      setCanPhoto(false);
      ctx.takePhoto({
        quality: 'high',
        success: (res) => {
          my.showLoading({
            content: '加载中...',
          })
          try{
            cloud.file.uploadFile({
              filePath: res.tempImagePath,  
              fileType: 'image',  
              fileName: 'file',
              formData: {
                file: res.tempImagePath, 
              },
              header: {
                'token': getStorageSync('token'),
                'user_type': 'taobao'
              },
            }).then((response) => {
              console.log('response', response);
              let {
                fileId,
                fileName,
                url
              } = response
              my.tb.imgRisk({
                data:{
                  cloudFileId: fileId
                },  
                success(res) { 
                  // setSuggestion(res.data.result.suggestion)
                },  
                fail() {
                  my.alert({ title: '检查失败' });
                }, 
              });
            })
            my.uploadFile({
              url: `https://jala-test-api.sndaurl.cn/v1/user/archives/upload`,
              filePath: res.tempImagePath,
              fileType: 'image',
              fileName: 'file',
              formData: {
                file: res.tempImagePath,
              },
              header: {
                'token': getStorageSync('token')
              },
              success: function (response) {
                let data = JSON.parse(response.data);
                setHasResult(true);
                my.hideLoading({});
                if (data.error) {
                  setError(data.error)
                  setPhoto(res.tempImagePath);
                  setIsOpen(true);
                } else {
                  setPhoto(data.url);
                }
                setCanPhoto(true);
              },
              fail: function (res) {
              }
            });
          } catch(e) {
            // my.alert({
            //     content: 'error ' + e.message  
            // });  
            console.log(e.message);
          }
        }
      })
    }
  }

  const doReset = () => {
    setIsOpen(false);
    my.navigateBack({});
  }

  const onSubmit = () => {
    let params = {
      url: photo
    }
    if (canSubmit) {
      setCanSubmit(false);
      postUserArchivesAdd(params)
        .then(res=>{
          let app = getApp();
          app.globalData.needRelaodFaceprofile = true;
          setCanSubmit(true);
          my.showToast({
            content: '添加成功',
            duration: 2000,
            type: 'none'
          })
          setTimeout(()=>{
            my.navigateBack();
          }, 2000)
        })
        .catch(err=>{
          setCanSubmit(true);
        })
    }
  }

  const onClose = () => {
    setIsOpen(false);
    my.navigateBack();
  }

  const onChangeOverturn = () => {
    if (positionType == 'front') {
      setPositionType('back')
    } else {
      setPositionType('front')
    }
  }

  return (
    <View className="camera_view">
      {
        hasResult ? (
          <Image
            source={{
              uri: photo
            }}
            className="camera"
            mode='aspectFill'
          />
        ) : (
          <View>
            <camera
              id="camera_take" 
              mode="normal" 
              device-position={positionType} 
              quality='high'
              className="camera"
            />
            <Image
              source={{
                uri: photoMask
              }}
              className="camera_view_modal"
              mode='aspectFill'
              style={{
                top: `${top}px`
              }}
            />
          </View>
        )
      }
      {
        hasResult ? (
          <View className="camera_view_actions">
            <View className="camera_view_actions_item" onClick={()=>{doReset()}}>更换图片</View>
            <View className="camera_view_actions_item" onClick={()=>{onSubmit()}}>确定</View>
          </View>
        ) : (
          <View className="camera_view_action">
            {/* <View className="camera_view_action_cancel">取消</View> */}
            <View className="camera_view_action_photo" onClick={()=>{takePhoto()}}>
              <View className="camera_view_action_photo_center"></View>
            </View>
            <View className='camera_view_action_overturn' onClick={()=>{onChangeOverturn()}}>
              <Image
                source={{
                  uri: overturnIcon
                }}
                className='camera_view_action_overturn_icon'
              />
            </View>
          </View>
        )
      }
      {
        isOpen ? (
          <View className='mask'>
            <View className="tip_modal">
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/camera.png'
                }}
                catchTouchMove
                className='tip_modal_tipImg'
              />
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/closeIcon.png'
                }}
                mode='aspectFill'
                className='tip_modal_icon'
                catchTouchMove
                onClick={()=>{onClose()}}
              />
              <View className="tip_modal_title">未识别到脸部</View>
              <View className="tip_modal_desc">再试试看，拍一张更清晰的照片吧</View>
              <View className="tip_modal_content">
                <Text className="tip_modal_content_label">拍摄指南</Text>
                帮助您获得更好的变妆效果
              </View>
              <View className="tip_modal_list">
                {
                  errorsList.map(item=>
                    <View className="tip_modal_list_item" key={item.id}>
                      <Image
                        source={{
                          uri: item.icon
                        }}
                        mode='aspectFill'
                        className="tip_modal_list_item_img"
                      />
                      <View className="tip_modal_list_item_tip">
                        <Image
                          src='https://jala-test-images.sndaurl.cn/images/closeBg.png'
                          className="tip_modal_list_item_tip_icon"
                          mode='aspectFill'
                        />
                        {item.name}
                      </View>
                    </View>
                  )
                }
              </View>
              <View className="tip_modal_action" onClick={()=>{doReset()}}>重新上传</View>
            </View>
          </View>
        ) : null
      }
    </View>
  )
}
export default CameraSection;
